import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  DeviceEventEmitter,
  TextInput,
  TouchableOpacity,
  FlatList,
} from 'react-native';
import {
  Text,
  Container,
  Header,
  Left,
  Body,
  Right,
  Title,
  Item,
  List,
  ListItem,
  Thumbnail,
  Button,
  Icon,
  Image,
} from 'native-base';
import Theme from '../../../native-base-theme/variables/commonColor';
import {Loading, BlankBackground, ListFooter } from '../../../components';
import * as devicesRequest from '../../../services/devicesRequest';
import { produce } from 'immer';

class maintenanceRecord extends Component {
  equipmentCode = '';

  page = 1;

  rows = 5;

  constructor(props) {
    super(props);
    this.state = {
      errorTag: false,
      isError: false,
      showLoading: true,
      refreshing: false,
      listData: [],
      isMore: false,
    };
  }

  componentDidMount() {
    // 必须在这里声明，所以 ref 回调可以引用它
  }

  // 点击某行
  cellAction = (item) => {
    // console.log('===', item);
    const par = {
      fromNavigation: true,
      id: item.item.failureId,
      code: item.item.failureCode,
    };
    global.navigation.navigate({ routeName: 'Info', params: par });
  }

  // 查询检维修历史数据
  queryData = async (flag) => {
    const ajaxData = {
      equipmentCode: this.equipmentCode,
      page: this.page,
      rows: this.rows,
      // condition: '',
      // page: this.page,
      // rows: this.rows,
    };

    // console.log('=====', ajaxData);
    try {
      if (flag === 'refresh') {
        this.setState({ refreshing: true });
      }
      // this.setState({ showLoading: true });
      const list = await devicesRequest.getHistoryByEqpId(ajaxData);
      this.setState(produce(draft => {
        if (flag === 'refresh') {
          draft.listData = list.data;
        } else {
          draft.listData = draft.listData.concat(list.data);
        }
        draft.refreshing = false;
        draft.showLoading = false;
        draft.isMore = draft.listData.length < list.totalNum;
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false, showLoading: false });
    }
  };

  // 用来被父组件调用 （点击检维修历史Tabs）
  QueryMaintenanceHistory = (msg) => {
    this.equipmentCode = msg;
    this.page = 1;
    this.queryData('refresh');
  };

  // 刷新时候获取数据
  _onRefresh = () => {
    this.page = 1;
    this.queryData('refresh');
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.page = this.page + 1;
      this.queryData('load');
    }
  }

  // 列表上拉加载没有数据时
  _renderListFooter = () => (
    (this.state.listData.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  // 错误页面刷新方法
  _onInitRefresh = () => {
    this.page = 1;
    this.queryData('refresh');
  }

  // 每一行
  renderRow= (item) =>{
    let dotColor = '';
    switch (item.item.failureStatus) {
      case '10':
        dotColor = 'red';
        break;

      case '20':
        dotColor = '#19be6b';
        break;

      case '30':
        dotColor = '#2d8cf0';
        break;

      default:
        dotColor = '#2d8cf0';
        break;
    }
    return (
      <TouchableOpacity onPress={() => this.cellAction(item)}>
        <View style={{ backgroundColor: '#ffffff', borderRadius: 8, marginLeft: 8, marginRight: 8, marginBottom: 8, padding: 8 }}>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <View style={[styles.circle, { backgroundColor: dotColor }]} />
              <Text style={styles.odd} note numberOfLines={1}>故障单号:{item.item.failureCode}</Text>
            </View>
            <View>
              <Text style={styles.time} note numberOfLines={1}>申报时间:{item.item.declareTime && item.item.declareTime.length > 11 && item.item.declareTime.substring(11, item.item.declareTime.length)}</Text>
            </View>
          </View>
          <View>
            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', marginTop: 8 }}>
              <View style={{ flex: 2 }}>
                <Text style={{ fontSize: 15, color: Theme.myPrimary }}>故障类型：</Text>
              </View>
              <View style={{ flex: 5 }}>
                <Text note style={{ fontSize: 15 }} numberOfLines={1}>{item.item.failureTypeDesc}</Text>
              </View>
            </View>
            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
              <View style={{ flex: 2 }}>
                <Text style={{ fontSize: 15, color: Theme.myPrimary }}>现象：</Text>
              </View>
              <View style={{ flex: 5 }}>
                <Text note style={{ fontSize: 15 }} numberOfLines={1}>{item.item.failureDesc} {item.item.failureKeywords}</Text>
              </View>
            </View>
            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
              <View style={{ flex: 2 }}>
                <Text style={{ fontSize: 15, color: Theme.myPrimary }}>状态：</Text>
              </View>
              <View style={{ flex: 5 }}>
                <Text note style={{ fontSize: 15 }} numberOfLines={1}>{item.item.failureStatusDesc}</Text>
              </View>
            </View>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  render() {
    const { errorTag, listData, showLoading, isError, refreshing } = this.state;
    let FlatListHtml = <Loading />;
    if (listData.length === 0 && !showLoading) {
      // FlatListHtml = <Loading />;
      FlatListHtml = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
    } else {
      FlatListHtml = (
        <FlatList
          style={styles.tabContent}
          data={listData}
          renderItem={item => this.renderRow(item)}
          keyExtractor={(item, index) => item + index}
          onRefresh={this._onRefresh}
          refreshing={refreshing}
          onEndReachedThreshold={0.05}
          scrollEventThrottle={200}
          onEndReached={this._onEndReached}
          ListFooterComponent={this._renderListFooter}
        />
      );
    }
    return (
      FlatListHtml
    );
  }
}

const styles = StyleSheet.create({
  tabContent: {
    backgroundColor: Theme.myPrimary,
    color: '#ffffff',
    width: '100%',
    flex: 1,
    marginTop: 8,
  },
  circle: {
    height: 10,
    width: 10,
    borderRadius: 5,
    marginRight: 5,
  },
  odd: {
    // backgroundColor: theme.myPrimary,
    // color: '#ffffff',
    fontSize: 12,
  },
  time: {
    // backgroundColor: theme.myPrimary,
    // color: '#ffffff',
    fontSize: 12,
  },
  content: {
    backgroundColor: Theme.myPrimary,
    color: '#ffffff',
    fontSize: 12,
    paddingTop: 3,
    paddingBottom: 3,
    marginLeft: 30,
    alignItems: 'flex-end',
  },
  Text: {
    backgroundColor: Theme.myPrimary,
    color: '#ffffff',
    fontSize: 16,
    paddingTop: 3,
    paddingBottom: 3,
  },
  circle: {
    marginRight: 10,
    alignItems: 'center',
    justifyContent: 'center',
    width: 12,
    height: 12,
    backgroundColor: '#f76260',
    borderColor: 'green',
    borderStyle: 'solid',
    borderRadius: 15,
    paddingTop: 10,
    // paddingBottom: 3,
  },
  badge: {
    height: 10,
    width: 10,
    borderRadius: 5,
    marginRight: 5,
    marginTop: 5,
  },
});

export default maintenanceRecord;
